//
//  LGHeartRhythmController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/7/30.
//  心律监测

#import "LGHeartRhythmController.h"
//心电分析
#import "LGECGDetailViewController.h"
#import "LGECGDetailViewController2.h"
#import "LGECGDetailEmptyController.h"
#import "LGChartDetailAlertView.h"
#import "LGHeartRhythmHeadView.h"
#import "LGHeartRhythmChartView.h"
#import "LGHeartRhythmWarnCell.h"
#import "LGHeartRhythmRecordCell.h"
#import "LGPickerView.h"
@interface LGHeartRhythmController ()<LGHeartRhythmHeadDelegate,UITableViewDelegate,UITableViewDataSource,LGHeartRhythmChartDelegate>
/**   */
@property (nonatomic , strong)LGHeartRhythmHeadView *headView;
/**   */
@property (nonatomic , strong)LGHeartRhythmChartView *chartView;
/**   */
@property (nonatomic , strong)LGChartDetailAlertView *alertView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *monthBtn;
/**   */
@property (nonatomic , strong)UIView *footerView;
/**   */
@property (nonatomic , strong)NSDateFormatter *formatter;
/**   */
@property (nonatomic , strong)NSCalendar *calendar;
/**   */
@property (nonatomic , strong)NSDate *currentDate;
/**   */
@property (nonatomic , copy)NSString *startDate;
/**   */
@property (nonatomic , copy)NSString *endDate;
/**   */
@property (nonatomic , strong)NSArray *warnArray;
/**   */
@property (nonatomic , strong)NSArray *dataArray;
/**   */
@property (nonatomic , strong)NSDictionary *chartDic;
/**   */
@property (nonatomic , strong)NSMutableArray *openArray;
/**   */
@property (nonatomic , copy)NSString *monthString;

@end

@implementation LGHeartRhythmController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"心律监测";
    self.monthString = [self.formatter stringFromDate:[NSDate date]];
    self.gradientLayer.colors = @[(__bridge id)[UIColor colorWithString:@"#E5F1FF"].CGColor, (__bridge id)[UIColor colorWithString:@"#F3F9FE"].CGColor, (__bridge id)[UIColor colorWithString:@"#FFFFFF"].CGColor];
    self.gradientLayer.locations = @[@(0), @(0.4f), @(1.0f)];
    self.view.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
    [self.view addSubview:self.tableView];
    [self.tableView addSubview:self.alertView];
    [self requestHistoryData];
}

//模块被选中
-(void)viewWillAppearAction{

}

-(void)requestHistoryData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/bpList" parameters:@{@"timeframe":self.monthString,@"patient_id":self.patientid,@"type":@"ecg"} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            self.dataArray = returnData;
            [self.openArray removeAllObjects];
            for (NSInteger i=0; i<self.dataArray.count; i++) {
                [self.openArray addObject:@(i+2)];
            }
            [self.tableView reloadData];
        }
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    } error:^(NSError *error) {
        self.isfirst = NO;
        if(self.dataArray.count == 0){
            self.footerView.frame = CGRectMake(0, 0, Screen_W, viewPix(300));
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无记录" offset:viewPix(60)];
        }else{
            self.footerView.frame = CGRectMake(0, 0, Screen_W, 0.001);
        }
        self.tableView.tableFooterView = self.footerView;
    }];
}


-(void)requestData:(NSString *)startDate endDate:(NSString *)endDate{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/ecgEcharts" parameters:@{@"patient_id":self.patientid,@"start_date":startDate,@"end_date":endDate} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.headView.dataDic = returnData;
            self.warnArray = returnData[@"warnData"];
            self.chartDic = returnData[@"echats"];
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

/*
 NSDictionary *dic = @{@"right":self.rightArray[index] , @"warn":self.warnArray[index] , @"percent":self.percentArray[index] , @"warnData":self.warnDataArray[index]};
 */
-(void)showAlertView:(NSDictionary *)dataDic date:(NSString *)dateString point:(CGPoint)point{
    
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:@[
                                 @{@"icon":@"",@"title":@"总测量",@"score":[NSString stringWithFormat:@"%ld次",[dataDic[@"right"] integerValue]+[dataDic[@"warn"] integerValue]],@"status":@"",@"color":@"#606266"},
                                 @{@"icon":@"心律监测-未见异常",@"title":@"未见异常",@"score":[NSString stringWithFormat:@"%@次",dataDic[@"right"]] ,@"status":@"",@"color":@"#606266"},
                                 @{@"icon":@"心律监测-异常心律占比",@"title":@"异常心律占比",@"score":[NSString stringWithFormat:@"%@次",dataDic[@"percent"]] ,@"status":@"",@"color":@"#606266"},
                                 @{@"icon":@"心律监测-异常心律",@"title":@"异常心律",@"score":[NSString stringWithFormat:@"%@次",dataDic[@"warn"]] ,@"status":@"",@"color":@"#606266"}]];
    NSArray *warnArray = dataDic[@"warnData"];
    for (NSDictionary *tempDic in warnArray) {
        NSDictionary *dic = @{@"icon":@"",@"title":LGNSString(tempDic[@"title"]),@"score":[NSString stringWithFormat:@"%@次",tempDic[@"count"]] ,@"status":@"",@"color":@"#AAAAAA"};
        [tempArray addObject:dic];
    }
    
    
    CGFloat marginX = (point.x>Screen_W/2.0)?(point.x-viewPix(140)-5):(point.x+5);
    self.alertView.frame = CGRectMake(marginX, point.y+3, viewPix(140), viewPix(35)+viewPix(24)*tempArray.count);
    self.alertView.dateString = dateString;
    self.alertView.dataArray = tempArray;
    self.alertView.hidden = NO;
    [self.tableView bringSubviewToFront:self.alertView];
//    if(point.x>Screen_W/2.0){
//        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.alertView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(15, 15)];
//        self.alertView.cornerLayer.path = path.CGPath;
//    }else{
//        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.alertView.bounds byRoundingCorners: UIRectCornerTopRight|UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(15, 15)];
//        self.alertView.cornerLayer.path = path.CGPath;
//    }
}


//选择月份
-(void)selecteMonthAction{
    NSMutableArray *yearArray = [NSMutableArray array];
    NSArray *monthArray = @[@"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12"];
    for (NSInteger i=2020; i<2100; i++) {
        [yearArray addObject:[NSString stringWithFormat:@"%ld",i]];
    }
    LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[yearArray,monthArray];
    pickerView.titleLabel.text = @"请选择月份";
    pickerView.units = @[@"年",@"月"];
    pickerView.selectStr = [self.monthString stringByReplacingOccurrencesOfString:@"-" withString:@"|"];
    [self.view.window addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickViewResult = ^(NSArray *resultArray) {
        [weakSelf.openArray removeAllObjects];
        weakSelf.monthString = [NSString stringWithFormat:@"%@-%@",resultArray[0],resultArray[1]];
        [weakSelf requestHistoryData];
    };
}

-(void)setMonthString:(NSString *)monthString{
    _monthString = monthString;
    NSArray *resultArray = [monthString componentsSeparatedByString:@"-"];
    [self.monthBtn setTitle:[NSString stringWithFormat:@"%@年%@月",resultArray[0],resultArray[1]] forState:UIControlStateNormal];
}

//历史记录 -- 展开、收起
-(void)openButtonAction:(UIButton *)sender{
    NSInteger index = sender.tag - 5000;
    if ([self.openArray containsObject:@(index)]) {
        [self.openArray removeObject:@(index)];
    }else{
        [self.openArray addObject:@(index)];
    }
    [self.tableView reloadData];
}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    self.alertView.hidden = YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2+self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return (self.warnArray.count>0)?1:0;
    }else if (section >= 2){
        NSArray *tempArray = self.dataArray[section-2][@"children"];
        return [self.openArray containsObject:@(section)]?tempArray.count:0;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //警告
        LGHeartRhythmWarnCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dataArray = self.warnArray;
        return cell;
    }else if (indexPath.section >= 2){
        //历史记录
        LGHeartRhythmRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:@"recordCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *tempArray = self.dataArray[indexPath.section-2][@"children"];
        cell.dataDic = tempArray[indexPath.row];
        cell.type = (indexPath.row == tempArray.count-1)?LGPositionTypeBottom:LGPositionTypeMiddle;
        return cell;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section >= 2){
        //心电分析
        NSDictionary *tempDic = self.dataArray[indexPath.section-2][@"children"][indexPath.row];
        NSString *source = LGNSString(tempDic[@"source"]);
        if ([source isEqualToString:@"BP"] || [source isEqualToString:@"add"]) {
            //心电图1
            LGECGDetailViewController *controller = [[LGECGDetailViewController alloc]init];
            controller.ecgId = LGNSString(tempDic[@"ecg_id"]);
            controller.patientid = self.patientid;
            [self.navigationController pushViewController:controller animated:YES];
        }else if ([source isEqualToString:@"KPQ"]||[source isEqualToString:@"KPQ6"]){
            //卡帕奇 、 卡帕奇6导
            NSString *warm = LGNSString(tempDic[@"ecg_warm"]);
            if ([warm isEqualToString:@"2"]) {
                //干扰数据
                LGECGDetailEmptyController *controller = [[LGECGDetailEmptyController alloc]init];
                controller.source = source;
                [self.navigationController pushViewController:controller animated:YES];
                
            }else{
                LGECGDetailViewController2 *controller = [[LGECGDetailViewController2 alloc]init];
                controller.ecgId = LGNSString(tempDic[@"ecg_id"]);
                controller.patientid = self.patientid;
                controller.source = source;
                [self.navigationController pushViewController:controller animated:YES];
            }
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section == 1){
        height = viewPix(92);
    }else if (section >= 2){
        height = viewPix(43);
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1){
        //历史记录
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(92))];
        UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(10))];
        topView.backgroundColor = [UIColor colorWithString:@"#F3F7F8"];
        [headView addSubview:topView];
        UILabel *titleLabel = [UILabel lableWithText:@"历史记录" colorString:@"#282828" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(18), viewPix(26), viewPix(150), viewPix(25));
        [headView addSubview:titleLabel];
        UIView *iconView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(20), viewPix(64), 4, viewPix(14))];
        iconView.backgroundColor = [UIColor colorWithString:@"#77D4C6"];
        iconView.cornerRidus = 2;
        [headView addSubview:iconView];
        [headView addSubview:self.monthBtn];
        UIImageView *tipView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"grayTipDown"]];
        [headView addSubview:tipView];
        [self.monthBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(iconView.mas_right).offset(viewPix(12));
            make.centerY.equalTo(iconView);
            make.width.equalTo(@(viewPix(110)));
            make.height.equalTo(@(viewPix(30)));
        }];
        [tipView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.right.equalTo(self.monthBtn);
            make.width.height.equalTo(@(16));
        }];
        return headView;
        
    }else if (section >= 2){
        //记录 -- 区头
        LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(43))];
        headView.topMargin = viewPix(8);
        UILabel *dateLabel = [UILabel lableWithText:self.dataArray[section-2][@"record_date"] colorString:@"#606266" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        dateLabel.frame = CGRectMake(viewPix(28), viewPix(18), viewPix(150), viewPix(22));
        [headView addSubview:dateLabel];
        UIButton *tipButton = [UIButton buttonWithImage:@"grayTipDown" selectImage:@"grayTipUp"];
        tipButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        tipButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, viewPix(16));
        tipButton.tag = 5000+section;
        tipButton.selected = [self.openArray containsObject:@(section)]?YES:NO;
        [tipButton addTarget:self action:@selector(openButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [headView addSubview:tipButton];
        [tipButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(headView).offset(-viewPix(16));
            make.left.equalTo(headView).offset(viewPix(16));
            make.height.equalTo(@(viewPix(40)));
            make.centerY.equalTo(dateLabel);
        }];
        return headView;
    }
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if (section == 0){
        height = viewPix(190);
    }else if (section >= 2){
        height = [self.openArray containsObject:@(section)]?0.01:viewPix(15);
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0){
        LGHeartRhythmChartView *chartView = [[LGHeartRhythmChartView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(190))];
        chartView.dataDic = self.chartDic;
        chartView.delegate = self;
        return chartView;
        
    }else if (section >= 2){
        CGFloat height = [self.openArray containsObject:@(section)]?0.01:viewPix(15);
        LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
        footView.bottomMargin = viewPix(8);
        return footView;
    }
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.tableView.frame = CGRectMake(0, 0, Screen_W, self.view.bounds.size.height);
}

-(LGHeartRhythmHeadView *)headView{
    if(!_headView){
        _headView = [[LGHeartRhythmHeadView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(270))];
        _headView.delegate = self;
    }
    return _headView;
}

-(NSDateFormatter *)formatter{
    if(!_formatter){
        _formatter = [[NSDateFormatter alloc]init];
        _formatter.dateFormat = @"yyyy-MM";
    }
    return _formatter;
}

-(LGChartDetailAlertView *)alertView{
    if(!_alertView){
        _alertView = [[LGChartDetailAlertView alloc] initWithFrame:CGRectMake(0, 0, viewPix(140), viewPix(50))];
        _alertView.hidden = YES;
    }
    return _alertView;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGHeartRhythmWarnCell class] forCellReuseIdentifier:@"cell"];
        [_tableView registerClass:[LGHeartRhythmRecordCell class] forCellReuseIdentifier:@"recordCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headView;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(15))];
    }
    return _tableView;
}

-(LGHeartRhythmChartView *)chartView{
    if(!_chartView){
        _chartView = [[LGHeartRhythmChartView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(200))];
        _chartView.delegate = self;
    }
    return _chartView;
}

-(UIButton *)monthBtn{
    if(!_monthBtn){
        _monthBtn = [UIButton buttonWithTitle:@"" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#282828" selectColor:@"#282828"];
        _monthBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [_monthBtn addTarget:self action:@selector(selecteMonthAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _monthBtn;
}

-(UIView *)footerView{
    if(!_footerView){
        _footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(300))];
        [self emptyViewWithSuperView:_footerView frame:_footerView.bounds];
    }
    return _footerView;
}

-(NSMutableArray *)openArray{
    if(!_openArray){
        _openArray = [NSMutableArray array];
    }
    return _openArray;
}

@end
